package com.adwin.addcoin.ui.main

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.adwin.addcoin.AddCoinApplication
import com.adwin.addcoin.R
import com.adwin.addcoin.base.BaseFragment
import com.adwin.addcoin.databinding.MainHomeFragmentBinding
import com.adwin.addcoin.repository.bean.HomeTaskBean
import com.adwin.addcoin.ui.adapter.TaskItemAdapter
import com.adwin.addcoin.ui.webview.WebViewActivity
import com.adwin.addcoin.utils.FlowKeyUtils
import com.adwin.addcoin.utils.PersonalMessageUtils
import com.adwin.addcoin.utils.installRepost
import com.bumptech.glide.Glide
import com.cashbird.app.infra.utils.FlowBus
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.MaterialHeader
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import org.json.JSONObject
import java.math.BigDecimal

class HomeFragment : BaseFragment<MainHomeFragmentBinding, MainViewModel>(
    MainHomeFragmentBinding::inflate,
    MainViewModel::class.java,
//是否使用publicViewModel
    false
) {
    private var pageNumber = 0
    private var isLoading = true
    lateinit var binding: MainHomeFragmentBinding
    private var images = arrayListOf<String>("")
    private var inviteUrl = ""
    private var exchangeUrl = ""
    private var withdrawUrl = ""

    private var tasks = ArrayList<HomeTaskBean>()

    private fun addTabString(arrays:Array<String>){
        for (message in arrays) {
            val view = LayoutInflater.from(this.context).inflate(R.layout.home_view_flipper_layout,null)
            view.findViewById<TextView>(R.id.tv_trumpet_title).text =message
            binding.vfHomeTrumpet.addView(view)
        }
    }

    @SuppressLint("MissingInflatedId")
    override fun initFragment(binding: MainHomeFragmentBinding, savedInstanceState: Bundle?) {
        this.binding = binding
        if (AddCoinApplication.isCloak){
            val trumpetTitle = resources.getStringArray(R.array.trumpet_title)
            addTabString(trumpetTitle)
        }else{
            val trumpetTitle = resources.getStringArray(R.array.trumpet_wt_title)
            addTabString(trumpetTitle)
        }

        binding.homeBanner.addBannerLifecycleObserver(this).setAdapter(object :
            BannerImageAdapter<String>(images){
            override fun onBindView(
                holder: BannerImageHolder?,
                data: String?,
                position: Int,
                size: Int
            ) {
                holder?.imageView?.let {
                    Glide.with(it.context).load(R.mipmap.add_coins_banner_icon).into(holder.imageView)
                    holder.imageView.setOnClickListener {
                        if (!TextUtils.isEmpty(inviteUrl)){
                            val intent = Intent(context,WebViewActivity::class.java)
                            intent.putExtra("url",inviteUrl)
                            startActivity(intent)
                        }
                    }
                }
            }
        })
        binding.srlTaskRefresh.setRefreshHeader(MaterialHeader(context))
        binding.srlTaskRefresh.setRefreshFooter(ClassicsFooter(context))
        binding.srlTaskRefresh.setOnRefreshLoadMoreListener(object :OnRefreshLoadMoreListener{
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                loading()
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                refresh()
            }
        })
        binding.rvTaskItem.adapter = context?.let { TaskItemAdapter(tasks, it) }
        binding.rvTaskItem.layoutManager = LinearLayoutManager(context,LinearLayoutManager.VERTICAL,false)
        binding.homeTopView.tvHomeWithdraw.setOnClickListener {
            val intent = Intent(context,WebViewActivity::class.java)
            if (AddCoinApplication.isCloak){
                if (TextUtils.isEmpty(exchangeUrl)) return@setOnClickListener
                intent.putExtra("url",exchangeUrl)
                MainScope().launch (Dispatchers.IO){
                    val obj = JSONObject()
                    obj.put("addCoinUrl",exchangeUrl)
                    context?.installRepost("clickHomeExchange",obj)
                }
            }else{
                if (TextUtils.isEmpty(withdrawUrl)) return@setOnClickListener
                intent.putExtra("url",withdrawUrl)
                MainScope().launch (Dispatchers.IO){
                    val obj = JSONObject()
                    obj.put("addCoinUrl",withdrawUrl)
                    context?.installRepost("clickHomeWithdraw",obj)
                }
            }
            startActivity(intent)
        }
        PersonalMessageUtils.userCoinsBean.observe(this){
            it?.let {
                binding.homeTopView.tvHomeCoin.text = "${BigDecimal(it.coinNum).setScale(0)}"
                binding.homeTopView.tvBonus.text = "= Rp${BigDecimal(it.conversionNum).setScale(2)}"
            }
        }
        PersonalMessageUtils.appDispositionBean.observe(this){appDisposition ->
            if (appDisposition != null){
                inviteUrl = appDisposition.INVITE
                exchangeUrl = appDisposition.EXCHANGE
                withdrawUrl = appDisposition.WITHDRAW
            }
        }
        if (AddCoinApplication.isCloak){
            binding.homeTopView.tvBonus.visibility = View.GONE
        }else{
            binding.homeTopView.tvBonus.visibility = View.VISIBLE
        }
        myViewModel?.isLoad?.observe(this){
            binding.srlTaskRefresh.setEnableLoadMore(it)
        }
        myViewModel?.taskLists?.observe(this){taskLists ->
            tasks.clear()
            tasks.addAll(taskLists)
            binding.rvTaskItem.adapter?.notifyDataSetChanged()
        }
        myViewModel?.isRefresh?.observe(this){
            if (!it){
                binding.srlTaskRefresh.finishLoadMore()
                binding.srlTaskRefresh.finishRefresh()
            }
        }
        if (AddCoinApplication.isCloak){
            binding.homeTopView.tvHomeWithdraw.text = resources.getString(R.string.main_home_exchange_button)
        }else{
            binding.homeTopView.tvHomeWithdraw.text = resources.getString(R.string.main_home_withdraw_button)
        }
        refresh()
        FlowBus.with<String>(FlowKeyUtils.taskChange).register(lifecycle){
            refresh()
        }
    }
    /**
     * 刷新数据
     */
    private fun refresh(){
        pageNumber = 1
        myViewModel?.getTaskList(pageNumber)
    }

    /**
     * 加载更多
     */
    private fun loading(){
        pageNumber++
        myViewModel?.getTaskList(pageNumber)
    }

    override fun onBackPressed(): Boolean = true

    override fun onStart() {
        super.onStart()
        binding.homeBanner.start()
        binding.vfHomeTrumpet.startFlipping()
    }

    override fun onStop() {
        super.onStop()
        binding.homeBanner.stop()
        binding.vfHomeTrumpet.stopFlipping()
    }

    override fun onDestroyView() {
        binding.homeBanner.destroy()
        super.onDestroyView()
    }

}